package com.jueyue.dao.resource;

import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Strings;
import com.jueyue.dao.parse.ParseUtil;
import com.jueyue.dao.util.PackagesToScanUtil;
import com.jueyue.dao.util.PublicUtil;

/**
 * sql map的基础类 初始化加载所有sql放到缓存中来
 * 
 * @author jueyue 2013年8月9日
 */
public class SQLFileMap {

	private Logger logger = LoggerFactory.getLogger(SQLFileMap.class);

	public SQLFileMap() {
	}

	/**
	 * 扫描classPath下面的文件
	 */
	public void scanClassPathFiles(Object[] paths) {
		logger.info("开始加载所有的sql");
		for (int i = 0; i < paths.length; i++) {
			for (String path : PackagesToScanUtil.getClasses((String) paths[i],
					PublicUtil.getProperties("sqlsName").toLowerCase())) {
				if (Strings.isNullOrEmpty(path))
					continue;
				path = getRealPath(path);
				logger.debug("load sqlfiel-" + path);
				readSQLFromFile(Thread.currentThread().getContextClassLoader()
						.getResourceAsStream(path));
			}
		}

	}

	private void readSQLFromFile(InputStream ips) {
		Map<String, String> map = ParseUtil.getSQLS(ips);
		Iterator<String> it = map.keySet().iterator();
		String key, value;
		while (it.hasNext()) {
			key = it.next();
			value = getSqlText(map.get(key));
			SQLResource.getLoader().putTemplate(key, value);
		}
	}

	/**
	 * 除去无效字段
	 */
	private String getSqlText(String text) {
		return text.replaceAll("\\n", " ").replaceAll("\\t", " ")
				.replaceAll("\\s{1,}", " ").trim();
	}

	/**
	 * 把前面木有的.换成\
	 * 
	 * @date 2014年1月13日
	 * @param path
	 * @return
	 */
	private String getRealPath(String path) {
		path = path.replaceAll("\\.", "/");
		return path.substring(0, path.lastIndexOf("/")) + "."
				+ path.substring(path.lastIndexOf("/") + 1);
	}
}